package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.auth.mapper.IUserDao;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.*;
import com.koocloud.electroplatemanage.mapper.IncomePartJudgeMapper;
import com.koocloud.electroplatemanage.pojo.*;
import com.koocloud.electroplatemanage.pojo.mainpojo.WIP;
import com.koocloud.electroplatemanage.service.ProductionPlanService;
import com.koocloud.electroplatemanage.utils.HexUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.util.StringUtils;
import static com.koocloud.electroplatemanage.constant.MainWIPRouteConstant.*;

/**
 * @program: Information_platform
 * @description: 生产计划实现层
 * @author: xxc
 * @create: 2020-11-02 18:37
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class ProductionPlanServiceImpl implements ProductionPlanService {
    @Resource
    private IncomePartJudgeMapper incomePartJudgeMapper;
    @Resource
    private IncomePartUnitMapper incomePartUnitMapper;
    @Resource
    private ProductionPlanMapper productionPlanMapper;
    @Resource
    private IUserDao iUserDao;
    @Resource
    private DrawNoMapper drawNoMapper;
    @Resource
    private TypeWorkMapper typeWorkMapper;
    @Resource
    private MainProductionMapper mainProductionMapper;
    @Resource
    private ProductPlanUrgentMapper productPlanUrgentMapper;//生产计划加急
    @Resource
    private
    ProductionTaskMapper productionTaskMapper;
    Lock lock = new ReentrantLock();

    @Override
    public ResponseTemplate selectAllData(String page, String limit,String beginTime,String endTime, ProductionPlan productionPlan) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                lock.lock();
                int rows = -1;
                //开始查询在工表，状态为4的插入生产计划(排产)
                List<WIP> wipList= mainProductionMapper.selectAllWIPByLocation(SCHEDULING);
                if(!StringUtils.isEmpty(wipList)) {
                    for(WIP wip:wipList) {
                        //获取工单号
                        if(!StringUtils.isEmpty(wip.getWorkOrderNumber())) {
                            //数据库重复工单号校验
                            int count = productionPlanMapper.selectWorkOrderNumberCount(wip.getWorkOrderNumber());
                            if(count>0) {
                                continue;
                            }


                            ProductionPlan insertProductionPlan = new ProductionPlan();

                            if(!StringUtils.isEmpty(wip.getEntryPerson())) {
                                //设置创建人
                                insertProductionPlan.setCreator(wip.getEntryPerson());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryTime())) {
                                //设置创建时间
                                insertProductionPlan.setCreateTime(wip.getEntryTime());
                            }
                            if(!StringUtils.isEmpty(wip.getLine())) {
                                //设置线路
                                insertProductionPlan.setLine(wip.getLine());
                            }
                            String workOrderNumber = wip.getWorkOrderNumber();
                            //设置工单号
                            insertProductionPlan.setWorkOrderNumber(workOrderNumber);
                            //设置删除标志
                            insertProductionPlan.setDeleteFlag("1");
                            if(!"A".equals(workOrderNumber.substring(workOrderNumber.length()-1,workOrderNumber.length()))) {
                                continue;
                            }

                            //根据工单号查询台账表记录
                            IncomePartJudgeVo incomePartJudgeVo = incomePartJudgeMapper.selectByWorkOrderNumber(workOrderNumber);





                            if(!StringUtils.isEmpty(incomePartJudgeVo)) {
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getOrderNumber())) {
                                    //设置订单号
                                    insertProductionPlan.setOrderNumber(incomePartJudgeVo.getOrderNumber());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartUnitCode())) {
                                    //设置来件单位编码
                                    insertProductionPlan.setIncomePartUnitCode(incomePartJudgeVo.getIncomePartUnitCode());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartTime())) {
                                    //设置来件时间
                                    insertProductionPlan.setIncomePartTime(incomePartJudgeVo.getIncomePartTime());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartQuantity())) {
                                    //设置来件数量
                                    insertProductionPlan.setIncomePartQuantity(incomePartJudgeVo.getIncomePartQuantity());
                                    //当前单据数量
                                    insertProductionPlan.setCurrentQuantity(incomePartJudgeVo.getIncomePartQuantity());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getIncomePartJudgeResult())) {
                                    //设置来件验收结果
                                    insertProductionPlan.setIncomePartJudgeResult(incomePartJudgeVo.getIncomePartJudgeResult());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getInspector())) {
                                    //设置检验员编码
                                    insertProductionPlan.setInspector(incomePartJudgeVo.getInspector());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getDegreeUrgency())) {
                                    //设置紧急程度
                                    insertProductionPlan.setDegreeUrgency(incomePartJudgeVo.getDegreeUrgency());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getDrawNoCode())) {
                                    //设置图号编码
                                    insertProductionPlan.setDrawNoCode(incomePartJudgeVo.getDrawNoCode());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getModelNumber())) {
                                    //设置型号
                                    insertProductionPlan.setModelNumber(incomePartJudgeVo.getModelNumber());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getModelType())) {
                                    //设置型别
                                    insertProductionPlan.setModelType(incomePartJudgeVo.getModelType());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getPartName())) {
                                    //设置零件名称
                                    insertProductionPlan.setPartName(incomePartJudgeVo.getPartName());
                                }
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getTypeWorkCode())) {
                                    //设置工种编码
                                    insertProductionPlan.setTypeWorkCode(incomePartJudgeVo.getTypeWorkCode());
                                }
                                //设置生产计划加急标志
                                insertProductionPlan.setState("1");
                                if(!StringUtils.isEmpty(incomePartJudgeVo.getDegreeUrgency())) {
                                    //设置生产计划删除标志
                                    insertProductionPlan.setDeleteFlag("0");
                                    //设置生产计划加急标志
                                    insertProductionPlan.setState("2");
                                    BtProductPlanUrgent btProductPlanUrgent = new BtProductPlanUrgent();
                                    //设置加急生产计划工单号
                                    btProductPlanUrgent.setProductionPlanId(workOrderNumber);
                                    //获取目前的order
                                    String large_class="生产计划";
                                    String sub_class="生产计划加急";
                                    //获取排序号
                                    String productPlanUrgentOrder = HexUtil.getProductPlanUrgentOrder(large_class, sub_class);
                                    btProductPlanUrgent.setOrder(productPlanUrgentOrder);
                                    btProductPlanUrgent.setCreateTime(HexUtil.getCurrentDateForString());
                                    btProductPlanUrgent.setDeleteFlag("1");
                                    //插入生产计划加急表
                                    productPlanUrgentMapper.insert(btProductPlanUrgent);
                                }
                                rows=productionPlanMapper.insert(insertProductionPlan);
                                //记录成功插入条数
                            }

                        }
                    }
                }
                //在工表插入完成后开始查询
                if(StringUtils.isEmpty(wipList)||(wipList.size()>0&&rows>0)||(wipList.size()>=0&&rows==-1)) {
                    //开始分页
                    PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                    //如果不传就查询当天的
                    if (StringUtils.isEmpty(beginTime)) {
                        beginTime = HexUtil.getCurrentDate();
                    }
                    if (StringUtils.isEmpty(endTime)) {
                        endTime = HexUtil.getCurrentDate();
                    }

                    List<ProductionPlan> productionPlanList = productionPlanMapper.selectAllData(beginTime, endTime, productionPlan);
                    //构造分页实体
                    PageInfo<ProductionPlan> info = new PageInfo<>(productionPlanList);
                    if (info.getTotal() > 0) {
                        //查询到数据
                        return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                    } else {
                        //没有查询到数据
                        return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                    }
                }
                else {
                    return ResponseTemplate.builder().code(1).message("在工表数据导入失败").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }

    @Override
    public ResponseTemplate insert(ProductionPlan productionPlan,String userId) {
        try {
          /*  //获取主表的id
           int incomepartjudgeId= productionPlan.getIncomepartjudgeId();
           String orderNumber=  productionPlan.getOrderNumber();
            //根据主表id获取目前这个订单号按时间排序 处于第几位
            String num = String.valueOf(incomePartJudgeMapper.selectOrderByIdAndOrderNum(incomepartjudgeId,orderNumber));
            productionPlan.setBatchNumber(num);

            int id =productionPlanMapper.selectMaxId()+1;
            productionPlan.setId(String.valueOf(id));
            int row = incomePartJudgeMapper.updateById(productionPlan.getIncomepartjudgeId());*/
           // if(row>0) {
                lock.unlock();
                Date date = new Date();//获取当前的日期
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                String strDate = df.format(date);//获取String类型的时间
                //设置创建时间
                productionPlan.setCreateTime(strDate);
                productionPlan.setDeleteFlag("1");
                //设置创建人
                User user = iUserDao.selectByPk(userId);
                productionPlan.setCreator(user.getJobNum());

                productionPlan.setUpdateTime(null);
                productionPlan.setModifier(null);
                //没有异常并且插入数据条数大于0
                int rows = productionPlanMapper.insert(productionPlan);
                if (rows > 0) {
                    return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
                } else {//没有异常并且插入数据失败，原则上不出现
                    return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
                }

            //}
           /* else {
                return ResponseTemplate.builder().code(1).message("重置主表生产计划标志失败").count(0l).build();
            }*/

        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //出现异常返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description:
     *@Param: [id, incomePartJudgeId, deleteFlag]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/5
     */
    @Override
    public ResponseTemplate delete(String id,String incomePartJudgeId,String deleteFlag) {
        try {
            lock.lock();
            String ideleteFlag = null;
            int rows = 0;
            int row = 0;
            ProductionPlan productionPlan = productionPlanMapper.selectById(id);
            if (!StringUtils.isEmpty(productionPlan) && !StringUtils.isEmpty(productionPlan.getStartDate())){
                //获取当前日期
                Date currentDate = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateString=sdf.format(currentDate)+" 23:59:59";
                //当天结束日期时间
                Date dateEnd=sdf.parse(dateString);
                //开始时间
                Date productionPlanDate=sdf.parse(productionPlan.getStartDate());
                //判断要删除的数据是否为今天之后的数据
                if(productionPlanDate.getTime()<=dateEnd.getTime()){
                    return ResponseTemplate.builder().code(1).message("不能删除当天及之前的数据!").count(0l).build();
                }else {
                    //根据当前主表id查询一条数据
                    IncomePartJudgeVo incomePartJudgeVo = incomePartJudgeMapper.selectById(incomePartJudgeId);
                  /*  if (!StringUtils.isEmpty(incomePartJudgeVo)){
                        //判断是否为完成的记录
                        if(!StringUtils.isEmpty(incomePartJudgeVo.getTimeCompletedOne()) &&!StringUtils.isEmpty(incomePartJudgeVo.getQuantityCompleted())){
                            ideleteFlag = ONE;
                            rows = incomePartJudgeMapper.productPlanDelete(incomePartJudgeId,ideleteFlag);
                        }else {
                            ideleteFlag = TWO;
                            rows = incomePartJudgeMapper.productPlanDelete(incomePartJudgeId,ideleteFlag);
                        }
                        row = productionPlanMapper.delete(id,deleteFlag);
                    }else {//理论不存在
                        return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
                    }*/
                    //判断删除操作是否成功
                    row = productionPlanMapper.delete(id,deleteFlag);
                    if (row > 0) {
                        //删除成功返回数据
                        return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
                    }
                    else {
                        //删除失败返回提示
                        return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
                    }
                }
            }else {
                return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    @Override
    public ResponseTemplate update(ProductionPlan productionPlan,String userId) {
        try {
            lock.lock();
            ProductionPlan productPlan = productionPlanMapper.selectById(String.valueOf(productionPlan.getWorkOrderNumber()));
            if (!StringUtils.isEmpty(productPlan) && !StringUtils.isEmpty(productPlan.getStartDate())){
                //获取当前日期
                Date currentDate = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateString=sdf.format(currentDate)+" 23:59:59";
                //当天结束日期时间
                Date dateEnd=sdf.parse(dateString);
                //开始时间
                Date productPlanDate=sdf.parse(productPlan.getStartDate());
                //判断要修改的数据是否为今天之后的数据
                if(productPlanDate.getTime()<=dateEnd.getTime()) {
                    return ResponseTemplate.builder().code(1).message("不能修改当天及之前的数据!").count(0l).build();
                }else {
                    //设置创建人
                    User user = iUserDao.selectByPk(userId);
                    productionPlan.setModifier(user.getJobNum());
                    //没有异常并且修改数据条数大于0
                    int rows = productionPlanMapper.update(productionPlan);
                    if(rows>0) {
                        return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
                    }
                    else {//没有异常并且修改数据失败，原则上不出现
                        return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
                    }
                }
            }else {
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }
    /**
     *@Description:主表id查询数据(主表点击生产计划按钮时跳生产计划新增时调用)
     *@Param: [id]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/2
     */
    @Override
    public ResponseTemplate selectByIncomePartId(String id) {
        try{
            //新建来料接收与判定实体
            IncomePartJudgeVo incomePartJudgeVo = null;
            incomePartJudgeVo = incomePartJudgeMapper.selectById(id);
            //判断查表操作是否成功
            if (null != incomePartJudgeVo) {
                ProductionPlan productionPlan = new ProductionPlan();
                //设置订单号
                productionPlan.setOrderNumber(incomePartJudgeVo.getOrderNumber());
                //设置来件单位
                IncomePartUnitVo incomePartUnitVo =incomePartUnitMapper.selectByPk(incomePartJudgeVo.getIncomePartUnitCode());
                if(!StringUtils.isEmpty(incomePartUnitVo)) {
                    //设置来件单位名称
                    productionPlan.setIncomePartUnitName(incomePartUnitVo.getCnName());
                }
                //设置来件单位编码
                productionPlan.setIncomePartUnitCode(incomePartJudgeVo.getIncomePartUnitCode());
                //设置来件时间
                productionPlan.setIncomePartTime(incomePartJudgeVo.getIncomePartTime());
                //设置来件数量
                productionPlan.setIncomePartQuantity(incomePartJudgeVo.getIncomePartQuantity());
                //设置来件验收结果
                productionPlan.setIncomePartJudgeResult(incomePartJudgeVo.getIncomePartJudgeResult());
                //设置检验员
                User user = iUserDao.selectByJobNum(incomePartJudgeVo.getInspector());
                if(!StringUtils.isEmpty(user)) {
                    //设置检验员名称
                    productionPlan.setInspectorName(user.getFullname());
                }
                //设置检验员编码
                productionPlan.setInspector(incomePartJudgeVo.getInspector());
                //设置紧急程度
                productionPlan.setDegreeUrgency(incomePartJudgeVo.getDegreeUrgency());
                //设置图号编码
                DrawNoVo drawNoVo = drawNoMapper.selectByPk(incomePartJudgeVo.getDrawNoCode());
                if(!StringUtils.isEmpty(drawNoVo)) {
                    //设置图号名称
                    productionPlan.setDrawNoName(drawNoVo.getName());
                }
                //设置图号编码
                productionPlan.setDrawNoCode(incomePartJudgeVo.getDrawNoCode());

                //设置型号
                productionPlan.setModelNumber(incomePartJudgeVo.getModelNumber());
                //设置型别
                productionPlan.setModelType(incomePartJudgeVo.getModelType());
                //设置零件名称
                productionPlan.setPartName(incomePartJudgeVo.getPartName());

                //设置工种及线路
                TypeWorkVo typeWorkVo = typeWorkMapper.selectByPk(incomePartJudgeVo.getTypeWorkCode());
                if(!StringUtils.isEmpty(typeWorkVo)) {
                    //设置工种名称
                    productionPlan.setTypeWorkName(typeWorkVo.getName());
                    //设置线路
                    if(!StringUtils.isEmpty(typeWorkVo.getLine())) {
                        productionPlan.setLine(typeWorkVo.getLine());
                    }

                }

                //设置工种编码
                productionPlan.setTypeWorkCode(incomePartJudgeVo.getTypeWorkCode());
                //设置主表id
                //productionPlan.setIncomepartjudgeId(incomePartJudgeVo.getId());
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(productionPlan).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        }
        catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }
}
